﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SortReference
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			OpenFileDialog ofd = new OpenFileDialog();
			ofd.Filter = "文本文件|*.txt";
			if (ofd.ShowDialog() != DialogResult.OK)
				return;
			string filePath = ofd.FileName;
			StreamReader sr = new StreamReader(filePath);
			string fileDirectory=Path.GetDirectoryName(filePath);
			string strLine=string.Empty;
			List<string> inPutRefs = new List<string>();
			List<string> newInPutRefs = new List<string>();
			List<string> CanntProcess = new List<string>();
			while ((strLine = sr.ReadLine()) != null)
			{
				strLine = strLine.Trim();
				if (!inPutRefs.Contains(strLine))
				{
					inPutRefs.Add(strLine);

					string regexExp = @"[.,，] [12][089]\d{2}";
					Regex reg = new Regex(regexExp);
					MatchCollection mc = reg.Matches(strLine);
					if (mc.Count !=1)
					{
						CanntProcess.Add(strLine);
						continue;
					}
					string res = mc[0].Value;
					regexExp = @" [12][089]\d{2}";
					reg = new Regex(regexExp);
					Match m = reg.Match(res);
					string year = m.Value;

					string[] array = strLine.Split('.');    
					string Author = array[0];

					string newString = Author + "#$" + year + "#$" + strLine;
					newInPutRefs.Add(newString);
				}

			}
			newInPutRefs.Sort();
			string savePath = fileDirectory + "\\SortedRef.txt";
			StreamWriter sw = new StreamWriter(savePath);
			foreach(string s in newInPutRefs)
			{
				string[] arrays = s.Split(new char[2]{'#','$'});
				sw.WriteLine(arrays.Last());

			}

			if(CanntProcess.Count!=0)
			{
				sw.WriteLine("\n未能够识别的文本：");
				foreach (string  s in CanntProcess)
				{
					sw.WriteLine(s);
				}
			}

			sw.Close();
			if (DialogResult.Yes == MessageBox.Show("处理完成，结果保存到SortedRef.txt文件中。是否立即打开文件？", "输出成功", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
			{
				System.Diagnostics.Process.Start("explorer.exe", "/select," + savePath);
			}

		}

	}
}
